<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  energyUsage: {
    type: Object,
    required: true,
    default: () => ({
      total: 0,
      proportions: []
    })
  }
})

// 图表实例
let energyPieChart = null

// 引用
const energyPieRef = ref(null)

// 初始化饼图
const initEnergyPie = () => {
  if (energyPieChart) {
    energyPieChart.dispose()
  }
  
  energyPieChart = echarts.init(energyPieRef.value)
  
  if (!props.energyUsage || !props.energyUsage.proportions || props.energyUsage.proportions.length === 0) {
    energyPieChart.setOption({
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'center',
        textStyle: {
          color: '#fff',
          fontSize: 16
        }
      }
    })
    return
  }
  
  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        if (!params || !params.data) return '暂无数据';
        return `${params.name}: ${params.data.value} (${params.data.percentage || '0%'})`;
      }
    },
    color: ['#67C23A', '#E6A23C', '#409EFF', '#F56C6C'],
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'center',
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      formatter: function(name) {
        const item = props.energyUsage.proportions.find(i => i.name === name);
        return `${name} - ${item.percentage}`;
      }
    },
    series: [
      {
        name: '能源使用',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 5,
          borderColor: '#000c1a',
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: false
          }
        },
        labelLine: {
          show: false
        },
        data: props.energyUsage.proportions.map(item => ({
          value: item.value,
          name: item.name
        }))
      }
    ]
  };
  
  energyPieChart.setOption(option);
}

// 监听数据变化重新渲染图表
watch(() => props.energyUsage, () => {
  initEnergyPie()
}, { deep: true })

// 窗口大小改变时重绘图表
const handleResize = () => {
  energyPieChart && energyPieChart.resize()
}

onMounted(() => {
  setTimeout(() => {
    initEnergyPie()
    window.addEventListener('resize', handleResize)
  }, 0)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  energyPieChart && energyPieChart.dispose()
})
</script>

<template>
  <dv-border-box-12 class="dashboard-panel">
    <div class="panel-header">能源使用分布</div>
    <div class="chart-container energy-pie" ref="energyPieRef"></div>
  </dv-border-box-12>
</template>

<style scoped>
.energy-pie {
  height: 95%;
}
</style> 